/*
 * $RCSfile: User.js,v $
 * $Revision: 1.1 $
 * $Date: 2014-04-18 $
 *
 * Copyright (C) 2008 Skin, Inc. All rights reserved.
 * This software is the proprietary information of Skin, Inc.
 * Use is subject to license terms.
 */
(function() {
if(typeof(Class) == "undefined") {
    Class = {};
}

/**
 * create a class
 * function Animal(){
 *     this.move = function(){logger.debug("move");};
 *     logger.debug("I am great !");
 * };
 * var Duck = Class.create(Animal, function(){
 *    this.swim = function(){
 *        logger.debug("help! help!");
 *    };
 *    logger.debug("I am very great !");
 * });
 * @param parent
 * @param constructor
 * @return Object
 */
Class.create = function(parent, constructor){
    var clazz = null;

    if(parent != null) {
        if(constructor != null) {
            clazz = function(){/* Class.create */ parent.apply(this, arguments); this.$super = Class.$super(this, parent.prototype); constructor.apply(this, arguments);};
        }
        else {
            clazz = function(){/* Class.create */ parent.apply(this, arguments); this.$super = Class.$super(this, parent.prototype);};
        }

        for(var property in parent.prototype) {
            clazz.prototype[property] = parent.prototype[property];
        }
    }
    else {
        if(constructor != null) {
            clazz = function(){/* Class.create */ this.$super = {}; constructor.apply(this, arguments);};
        }
        else {
            clazz = function(){/* Class.create */ this.$super = {};};
        }
    }

    return (clazz.prototype.constructor = clazz);
};

/**
 * @param prototype
 * @param instance
 * @retur Object
 */
Class.$super = /* private */ function(instance, prototype){
    var object = {};

    for(var i in prototype) {
        if(typeof(prototype[i]) == "function") {
            object[i] = function(){prototype[i].apply(instance, arguments);};
        }
    }

    return object;
};

/**
 * simple singleton
 * var myduck = Class.getInstance(Animal, function(){this.swim = function(){};});
 * myduck.swim();
 * @param parent
 * @param constructor
 * @return Object
 */
Class.getInstance = function(parent, constructor){
    return new (Class.create(parent, constructor))();
};

/**
 * extend properties
 * @param child
 * @param parent
 * @return Object
 */
Class.extend = function(child, parent){
    if(child == null) {
        child = {};
    }

    for(var property in parent) {
        child[property] = parent[property];
    }

    return child;
};

var CookieUtil = {};
CookieUtil.trim = function(s){return (s != null ? s.replace(/(^\s*)|(\s*$)/g, "") : "");};
CookieUtil.nval = function() {
    var i = 0;
    var e = null;

    for(i = 0; i < arguments.length; i++) {
        e = arguments[i];

        if(e == null || e == undefined) {
            continue;
        }

        if(typeof(e) == "string") {
            e = CookieUtil.trim(e);

            if(e.length > 0) {
                return e;
            }
        }
        else {
            return e;
        }
    }
    return null;
};
CookieUtil.setCookie = function(cookie) {
    var expires = "";
    if(cookie.value == null) {
        cookie.value = "";
        cookie.expires = -1;
    }

    if(cookie.expires != null) {
        var date = null;

        if(typeof(cookie.expires) == "number") {
            date = new Date();
            date.setTime(date.getTime() + cookie.expires * 1000);
        }
        else if(cookie.expires.toUTCString != null) {
            date = cookie.expires;
        }

        // use expires attribute, max-age is not supported by IE
        if(date != null) {
            expires = "; expires=" + date.toUTCString();
        }
    }
    var path = cookie.path ? "; path=" + (cookie.path) : "";
    var domain = cookie.domain ? "; domain=" + (cookie.domain) : "";
    var secure = cookie.secure ? "; secure" : "";
    document.cookie = [cookie.name, "=", (cookie.value != null ? encodeURIComponent(cookie.value) : ""), expires, path, domain, secure].join("");
};

CookieUtil.getCookie = function(name, defaultValue) {
    var value = null;

    if(document.cookie && document.cookie != "") {
        var cookies = document.cookie.split(';');

        for(var i = 0; i < cookies.length; i++) {
            var cookie = CookieUtil.trim(cookies[i]);

            if(cookie.substring(0, name.length + 1) == (name + "=")) {
                value = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return CookieUtil.nval(value, defaultValue);
};

CookieUtil.remove = function(name, path) {
    CookieUtil.setCookie({"name": name, "path": path});
};

var Base64 = {};

Base64.ENCODE_TABLE = [
    "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K",
    "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
    "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g",
    "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r",
    "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2",
    "3", "4", "5", "6", "7", "8", "9", "+", "/"
];

Base64.DECODE_TABLE = [
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
    52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
    -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
    15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
    -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
    41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1
];

Base64.encode = function(text) {
    var c1 = 0;
    var c2 = 0;
    var c3 = 0;

    var data = this.getBytes(text);
    var modulus = data.length % 3;
    var length = data.length - modulus;
    var buffer = [];

    for(var i = 0, j = 0; i < length; i += 3, j += 4) {
        c1 = data[i + 0] & 0xff;
        c2 = data[i + 1] & 0xff;
        c3 = data[i + 2] & 0xff;

        buffer[j + 0] = this.ENCODE_TABLE[((c1 >>> 2) & 0x3f)];
        buffer[j + 1] = this.ENCODE_TABLE[((c1 << 4) | (c2 >>> 4)) & 0x3f];
        buffer[j + 2] = this.ENCODE_TABLE[((c2 << 2) | (c3 >>> 6)) & 0x3f];
        buffer[j + 3] = this.ENCODE_TABLE[((c3 & 0x3f))];
    }

    var b4 = 0;
    var b5 = 0;

    if(modulus == 1) {
        b4 = data[data.length - 1] & 0xff;
        c1 = (b4 >>> 2) & 0x3f;
        c2 = (b4 << 4) & 0x3f;

        buffer[buffer.length] = this.ENCODE_TABLE[c1];
        buffer[buffer.length] = this.ENCODE_TABLE[c2];
        buffer[buffer.length] = "==";
    }
    else if(modulus == 2) {
        b4 = data[data.length - 2] & 0xff;
        b5 = data[data.length - 1] & 0xff;
        c1 = ((b4 >>> 2) & 0x3f);
        c2 = ((b4 << 4) | (b5 >>> 4)) & 0x3f;
        c3 = ((b5 << 2) & 0x3f);

        buffer[buffer.length] = this.ENCODE_TABLE[c1];
        buffer[buffer.length] = this.ENCODE_TABLE[c2];
        buffer[buffer.length] = this.ENCODE_TABLE[c3];
        buffer[buffer.length] = "=";
    }

    return buffer.join("");
};

Base64.decode = function(data) {
    var c1 = 0;
    var c2 = 0;
    var c3 = 0;
    var c4 = 0;
    var buffer = [];

    for(var i = 0, length = data.length; i < length;)  {
        do  {
             c1 = this.DECODE_TABLE[data.charCodeAt(i++) & 0xff];
        } 
        while(i < length && c1 == -1);

        if(c1 == -1) {
            break;
        }

        do  {
            c2 = this.DECODE_TABLE[data.charCodeAt(i++) & 0xff];
        }
        while(i < length && c2 == -1);

        if(c2 == -1) {
            break;
        }

        buffer[buffer.length] = (c1 << 2) | ((c2 & 0x30) >> 4);

        do  {
            c3 = data.charCodeAt(i++) & 0xff;
        
            if(c3 == 61) {
                return this.getString(buffer);
            }

            c3 = this.DECODE_TABLE[c3];
        } 
        while(i < length && c3 == -1);

        if(c3 == -1) {
            break;
        }

        buffer[buffer.length] = ((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2);

        do {
            c4 = data.charCodeAt(i++) & 0xff;

            if(c4 == 61) {
                return this.getString(buffer);
            }

            c4 = this.DECODE_TABLE[c4];
        } 
        while(i < length && c4 == -1);

        if(c4 == -1) {
            break;
        }

        buffer[buffer.length] = ((c3 & 0x03) << 6) | c4;
    }

    return this.getString(buffer);
};

Base64.getBytes = function(data) {
    var c;
    var buffer = [];

    for(var i = 0, length = data.length; i < length; i++) {
        c = data.charCodeAt(i);

        if((c >= 0x0001) && (c <= 0x007F)) {
            buffer[buffer.length] = c;
        }
        else if(c > 0x07FF) {
            buffer[buffer.length] = (0xE0 | ((c >> 12) & 0x0F));
            buffer[buffer.length] = (0x80 | ((c >>　6) & 0x3F));
            buffer[buffer.length] = (0x80 | ((c >>　0) & 0x3F));
        }
        else {
            buffer[buffer.length] = (0xC0 | ((c >>　6) & 0x1F));
            buffer[buffer.length] = (0x80 | ((c >>　0) & 0x3F));
        }
    }

    return buffer;
};

Base64.getString = function(data) {
    var c;
    var c1, c2;
    var buffer = [];

    for(var i = 0, length = data.length; i < length;) {
        c = data[i++];

        switch(c >> 4) {
            case 0:
            case 1:
            case 2:
            case 3:
            case 4:
            case 5:
            case 6:
            case 7: {
                buffer[buffer.length] = String.fromCharCode(data[i - 1]);
                break;
            }
            case 12:
            case 13: {
                c1 = data[i++];
                buffer[buffer.length] = String.fromCharCode(((c & 0x1F) << 6) | (c1 & 0x3F));
                break;
            }
            case 14: {
                c1 = data[i++];
                c2 = data[i++];
                buffer[buffer.length] = String.fromCharCode(((c & 0x0F) << 12) | ((c1 & 0x3F) << 6) | ((c2 & 0x3F) << 0));
                break;
            }
        }
    }
    return buffer.join("");
};

var Response = {};

Response.error = function(result) {
    alert("系统错误，请稍后再试！");
};

Response.success = function(result, success) {
    if(result == null) {
        alert("系统错误，请稍后再试！");
        return false;
    }

    if(result.code == 0 || result.status == 200) {
        if(success != null) {
            success(result.value);
        }
        return true;
    }

    if(result.message != null) {
        alert(result.message);
    }
    else{
        alert("系统错误，请稍后再试！");
    }
    return false;
};

var PageContext = {};

PageContext.getContextPath = function() {
    if(this.contextPath != null) {
        return this.contextPath;
    }

    var contextPath = this.getAttribute("contextPath");

    if(contextPath == null || contextPath == "/") {
        contextPath = "";
    }
    return (this.contextPath = contextPath);
};

PageContext.setAttribute = function(name, value) {
    var e = document.getElementById("pageContext");

    if(value == null || value == undefined) {
        e.removeAttribute(name);
    }
    else {
        e.setAttribute(name, value);
    }
};

PageContext.getAttribute = function(name, defaultValue) {
    var e = document.getElementById("pageContext");

    if(e == null) {
        return null;
    }
    var value = e.getAttribute(name);
    return (value != null ? value : defaultValue);
};

PageContext.getObject = function(name) {
    var data = this.getAttribute(name);

    if(data == null) {
        return null;
    }

    try {
        return window.eval("(" + data + ")");
    }
    catch(e) {
    }
    return null;
};

PageContext.getInt = function(name) {
    var value = this.getAttribute(name);
    if(value == null) {
        return 0;
    }
    value = parseInt(value);
    return (isNaN(value) ? 0 : value);
};

PageContext.getLong = function(name) {
    var value = this.getAttribute(name);
    if(value == null) {
        return 0;
    }
    value = parseInt(value);
    return (isNaN(value) ? 0 : value);
};

PageContext.getURL = function(path) {
    return window.location.protocol + "//" + window.location.host + this.getContextPath() + path;
};

function Listener(){
    this.listeners = [];
};

Listener.prototype.addListener = function(listener){
    this.listeners[this.listeners.length] = listener;
};

Listener.prototype.removeListener = function(listener){
    var listeners = this.listeners;
    if(listeners != null){
        var index = -1;
        for(var i = 0, length = listeners.length; i < length; i++){
            if(listener == listeners[i]){
                index = i;
                break;
            }
        }
        if(index > -1){
            for(var i=index,length=listeners.length-1;i<length;i++){
                listeners[i]=listeners[i+1];
            }
            listeners[listeners.length-1]=null;
            listeners.length=listeners.length-1;
            return listener;
        }
    }
    return null;
};

Listener.prototype.trigger = function(){
    var listeners=this.listeners;
    if(listeners!=null){
        for(var i=0,length=listeners.length;i<length;i++){
            try {
                var flag=listeners[i].apply(this,arguments);
                if(flag!=null&&flag!=undefined&&flag==false)
                {break;}
            }
            catch(e)
            {throw e;}
        }
    }
};

var Tooltip = {};

Tooltip.show = function(message) {
    var c = this.getContainer();

    jQuery(c).find("div.content").html(message);
    jQuery(c).css({"top": 0, "left": "50%", "display": "block"});
    jQuery(c).animate({"opacity": 0.0}, 3000);
};

Tooltip.hide = function() {
    jQuery(this.getContainer()).hide();
};

Tooltip.getContainer = function() {
    var c = document.getElementById("widget-tooltip");

    if(c == null) {
        c = document.createElement("div");
        c.id = "widget-tooltip";
        c.className = "widget-tooltip";
        c.innerHTML = "<div class=\"content\"></div>";
        document.body.appendChild(c);
    }
    return c;
};

jQuery.fn.extend({
    register: function(callback){
        var form = jQuery(this);
        var userName = form.find("input[name=userName]");
        var password = form.find("input[name=password]");
        var repassword = form.find("input[name=repassword]");
        var userEmail  = form.find("input[name=userEmail]");
        var nickName  = form.find("input[name=nickName]");

        var captchaTxt = form.find("input[name=captcha]");
        var captchaImg = form.find("img.captcha");
        var captchaBtn = form.find(".captcha_btn");
        var licence = form.find("input[name=licence]");
        var submit = form.find(".submit");
        var cancel = form.find(".cancel");

        userName.val("");
        captchaTxt.val("");

        if(form.attr("event-bind") == "true") {
            return;
        }

        form.attr("event-bind", "true");

        form.submit(function(){
            return false;
        });

        userName.focus(function(){
        });

        cancel.click(function() {
            window.location.href = "/index.html";
        });

        userName.blur(function(){
            var src = jQuery(this);
            var bind = src.attr("bind");
            var value = jQuery.trim(src.val());
            var showMessage = function(message) {
                jQuery(".user-name.message").html(message);
            };

            if(value.length < 1) {
                src.attr("bind", "");
                showMessage("");
            }
            else if(value != bind) {
                src.attr("bind", value);
                src.attr("result", "?");
                showMessage("正在检查用户名，请稍候...");

                jQuery.ajax({
                    type: "GET",
                    url: PageContext.getContextPath() + "/ajax/user/getUserByUserName.html?userName=" + encodeURIComponent(value) + "&callback=?",
                    dataType: "jsonp",
                    error: function(req) {
                        showMessage("<em class=\"error\"></em>系统错误，请稍后再试！");
                    },
                    success: function(data) {
                        if(data == null) {
                            showMessage("<em class=\"error\"></em>系统错误，请稍后再试！");
                            return;
                        }

                        if(data.status != 200) {
                            showMessage("<em class=\"error\"></em>" + data.message);
                            return;
                        }

                        var user = data.value;

                        if(user.userId != null) {
                            showMessage("<em class=\"error\"></em>此用户名已被占用！");
                        }
                        else {
                            src.attr("result", (data.status == 200 ? "0": "3"));
                            showMessage("<em class=\"ok\"></em>输入正确！");
                        }
                    }
                });
            }
        });

        nickName.focus(function(){
        });

        nickName.blur(function() {
            var src = jQuery(this);
            var bind = src.attr("bind");
            var value = jQuery.trim(src.val());

            var showMessage = function(message) {
                form.find(".nick-name.message").html(message);
            };

            if(value.length < 1) {
                src.attr("bind", "");
                showMessage("");
            }
            else if(value != bind) {
                src.attr("bind", value);
                src.attr("result", "?");
                showMessage("正在检查昵称，请稍候...");

                jQuery.ajax({
                    type: "GET",
                    url: PageContext.getContextPath() + "/ajax/user/getUserByNickName.html?nickName=" + encodeURIComponent(value) + "&callback=?",
                    dataType: "jsonp",
                    error: function(req) {
                        showMessage("<em class=\"error\"></em>系统错误，请稍后再试！");
                    },
                    success: function(data) {
                        if(data == null) {
                            showMessage("<em class=\"error\"></em>系统错误，请稍后再试！");
                            return;
                        }

                        if(data.status != 200) {
                            showMessage("<em class=\"error\"></em>" + data.message);
                            return;
                        }

                        var user = data.value;

                        if(user.userId != null) {
                            showMessage("<em class=\"error\"></em>此昵称已被占用！");
                        }
                        else {
                            src.attr("result", (data.status == 200 ? "0": "3"));
                            showMessage("<em class=\"ok\"></em>输入正确！");
                        }
                    }
                });
            }
        });

        password.blur(function(){
            var src = jQuery(this);
            var value = jQuery.trim(src.val());
            src.attr("result", "0");

            if(value.length < 1) {
                return;
            }

            if(value.length < 6 || value.length > 16) {
                src.attr("result", "1");
                form.find(".password.message").html("<em class=\"error\"></em>密码长度6-16位字符！");
                return;
            }

            if(value == jQuery.trim(userName.val())) {
                src.attr("result", "2");
                form.find(".password.message").html("<em class=\"error\"></em>密码不能和用户名相同！");
                return;
            }

            if(value.match(/^[a-zA-Z0-9]{6,16}$/g) == null) {
                src.attr("result", "3");
                form.find(".password.message").html("<em class=\"error\"></em>密码由a-z的不限大小写英文字母或0-9的数字组成！");
                return;
            }
            form.find(".password.message").html("<em class=\"ok\"></em>密码输入格式正确！");
            return;
        });

        password.keyup(function(){
            var src = jQuery(this);
            var value = jQuery.trim(src.val());
            var length = value.length;

            if(length < 6 || length > 16) {
                src.attr("result", "1");
                form.find(".password-suggest").empty();
                form.find(".password-suggest").attr("class", "password-suggest gray").html("无效");
                return;
            }

            src.attr("result", "0");

            var hasNumber = function(word){
                for(var i = 0; i < word.length; i++) {
                    var charCode = word.charCodeAt(i);
                    if(charCode >= 48 && charCode <= 58) {
                        return true;
                    }
                }
                return false;
            };

            var hasLowerCase = function(word){
                for(var i = 0; i < word.length; i++) {
                    var charCode = word.charCodeAt(i);
                    if(charCode >= 65 && charCode <= 90) {
                        return true;
                    }
                }
                return false;
            };

            var hasUpperCase = function(word){
                for(var i = 0; i < word.length; i++) {
                    var charCode = word.charCodeAt(i);
                    if(charCode >= 97 && charCode <= 122) {
                        return true;
                    }
                }
                return false;
            };

            var isHasNumber = hasNumber(value);
            var isHasLowerCase = hasLowerCase(value);
            var isHasUpperCase = hasUpperCase(value);

            if(isHasNumber && !isHasLowerCase && !isHasUpperCase) {
                form.find(".password-suggest").empty();
                form.find(".password-suggest").attr("class", "password-suggest red").html("低");
            }
            else if(length >= 8 && isHasNumber && isHasLowerCase && isHasUpperCase) {
                form.find(".password-suggest").empty();
                form.find(".password-suggest").attr("class", "password-suggest green").html("高");
            }
            else {
                form.find(".password-suggest").empty();
                form.find(".password-suggest").attr("class", "password-suggest blue").html("中");
            }
        });

        repassword.blur(function(){
            var src = jQuery(this);
            var value = jQuery.trim(src.val());

            if(password.attr("result") == "0") {
                if(value.length < 1) {
                    return;
                }

                if(value != jQuery.trim(password.val())) {
                    src.attr("result", "1");
                    form.find(".password.message").html("<em class=\"error\"></em>密码不一致，请重新输入！");
                }
                else {
                    src.attr("result", "0");
                    form.find(".password.message").html("<em class=\"ok\"></em>密码输入一致！");
                }
            }
        });

        userEmail.focus(function(){
        });

        userEmail.blur(function(){
            var src = jQuery(this);
            var bind = src.attr("bind");
            var value = jQuery.trim(src.val());
            var reg = /^([\w.])+\@(([\w])+\.)[a-zA-Z0-9]{2,}/;

            var showMessage = function(message) {
                form.find(".user-email.message").html(message);
            };

            if(value.length < 1) {
                src.attr("bind", "");
                showMessage("");
            }
            else if(!reg.test(value)) {
                src.attr("result", "1");
                form.find(".user-email.message").html("<em class=\"error\"></em>请输入正确邮箱地址！");
                return;
            }
            else if(value != bind) {
                src.attr("bind", value);
                src.attr("result", "?");
                showMessage("正在检查邮箱，请稍候...");

                jQuery.ajax({
                    type: "GET",
                    url: PageContext.getContextPath() + "/ajax/user/getUserByUserEmail.html?userEmail=" + encodeURIComponent(value) + "&callback=?",
                    dataType: "jsonp",
                    error: function(req) {
                        showMessage("<em class=\"error\"></em>系统错误，请稍后再试！");
                    },
                    success: function(data) {
                        if(data == null) {
                            showMessage("<em class=\"error\"></em>系统错误，请稍后再试！");
                            return;
                        }

                        if(data.status != 200) {
                            showMessage("<em class=\"error\"></em>" + data.message);
                            return;
                        }

                        var user = data.value;

                        if(user.userId != null) {
                            showMessage("<em class=\"error\"></em>此邮箱已使用，请更换其他邮箱！");
                        }
                        else {
                            src.attr("result", (data.status == 200 ? "0": "3"));
                            showMessage("<em class=\"ok\"></em>输入正确！");
                        }
                    }
                });
            }
        });

        captchaTxt.focus(function(){
            if(jQuery.trim(userName.val()) != "") {
                if(captchaImg.attr("status") != "1") {
                    captchaImg.show();
                    captchaBtn.show();
                    captchaImg.attr("status", "1");
                    captchaImg.css({"width": "100px", "height": "40px"});
                    captchaImg.attr("src", PageContext.getContextPath() + "/captcha?r=" + Math.random());
                }
            }
        });

        captchaBtn.click(function(){
            if(jQuery.trim(userName.val()) != "") {
                captchaImg.show();
                captchaImg.attr("src", PageContext.getContextPath() + "/captcha?r=" + Math.random());
            }
            return false;
        });

        captchaImg.click(function(){
            jQuery(this).show();
            jQuery(this).attr("src", PageContext.getContextPath() + "/captcha?r=" + Math.random());
        });

        form.find(".licencelabel").click(function(){
            if(licence.attr("checked") == true) {
                licence.attr("checked", false);
            }
            else {
                licence.attr("checked", true);
            }
        });

        submit.unbind();
        submit.click(function(){
            if(jQuery.trim(userName.val()) == "") {
                form.find(".user-name.message").html("<em class=\"error\"></em>用户名不能为空！");
                return false;
            }

            nickName.val(userName.val());
            nickName.attr("result", "0");

            if(nickName.size() > 0 && jQuery.trim(nickName.val()) == "") {
                form.find(".nick-name.message").html("<em class=\"error\"></em>昵称不能为空！");
                return false;
            }

            if(jQuery.trim(password.val()) == "") {
                form.find(".password.message").html("<em class=\"error\"></em>密码不能为空！");
                return false;
            }

            if(jQuery.trim(repassword.val()) == "") {
                form.find(".password.message").html("<em class=\"error\"></em>确认密码不能为空！");
                return false;
            }

            if(jQuery.trim(password.val()) != jQuery.trim(repassword.val())) {
                form.find(".password.message").html("<em class=\"error\"></em>密码不一致！");
                return false;
            }

            if(jQuery.trim(userName.attr("result")) != "0") {
                form.find(".user-name.message").html("<em class=\"error\"></em>用户名不合法！");
                return false;
            }

            if(nickName.size() > 0 && jQuery.trim(nickName.attr("result")) != "0") {
                form.find(".nick-name.message").html("<em class=\"error\"></em>昵称不合法！");
                return false;
            }

            if(jQuery.trim(userEmail.attr("result")) != "0") {
                form.find(".user-email.message").html("<em class=\"error\"></em>邮箱不合法！");
                return false;
            }

            /*
            if(jQuery.trim(captchaTxt.val()) == "") {
                alert("请输入验证码！");
                return false;
            }
            */

            if(licence.prop("checked") != true) {
                alert("请阅读用户注册协议！");
                return false;
            }

            if(form.attr("async") != "true") {
                jQuery(this).attr("disabled", "true");
                form.find("input[name=location]").val("");
                form.attr("method", "post");
                form.attr("action", PageContext.getContextPath() + "/user/register.html");
                form.get(0).submit();
            }
            else {
                window.callback = null;

                var request = {
                    method: "post",
                    action: PageContext.getContextPath() + "/user/register.html",
                    parameters: {
                        "userName": jQuery.trim(userName.val()),
                        "password": jQuery.trim(password.val()),
                        "repassword": jQuery.trim(repassword.val()),
                        "userEmail": jQuery.trim(email.val()),
                        "nickName": jQuery.trim(nickName.val()),
                        "captcha": jQuery.trim(captchatxt.val()),
                        "redirect": "http://" + location.host + "/callback.jsp"
                    }
                };

                var iframe = document.getElementById("proxyframe");

                if(iframe != null) {
                    var handler = function(code, message) {
                        if(code == null && message == null) {
                            return;
                        }

                        if(code == 0) {
                            window.user = UserManager.parse();

                            if(window.UserManager != null) {
                                UserManager.trigger(window.user);
                            }

                            if(callback != null) {
                                callback({"code": code, "message": message});
                            }
                        }
                        else {
                            alert(message);
                        }

                        captchatxt.val("");
                        captchabtn.click();
                    };

                    window.proxyFrameLoaded = function() {
                        var w = iframe.contentWindow.window;

                        if(w.JForm != null && w.JForm.submit != null) {
                            window.callback = handler;
                            w.JForm.submit(request);
                        }
                        else {
                            window.callback = null;
                        }
                    };
                    iframe.src = "http://" + location.host + "/jform.html";
                }
                else {
                    alert("系统错误, 请稍后重试 !");
                }
            }
            return false;
        });
    },
    login: function(callback){
        var form = jQuery(this);
        var userName = form.find("input[name=userName]");
        var password = form.find("input[name=password]");
        var captcha = form.find("input[name=captcha]");
        var captchaImg = form.find("img.captcha");
        var loginBtn = form.find("a.ensure");
        var cancelBtn = form.find("a.cancel");

        userName.focus();
        captcha.val("");
        loginBtn.attr("disabled", false);

        if(form.attr("initialized") != "true") {
            form.attr("initialized", "true");

            var keydown = function(event) {
                event.stopPropagation();

                if(event.keyCode == 13) {
                    loginBtn.click();
                }
            };

            userName.unbind();
            password.unbind();
            captcha.unbind();
            captchaImg.unbind();
            loginBtn.unbind();

            userName.click(function(event){
                event.stopPropagation();
            });

            password.click(function(event){
                event.stopPropagation();
            });

            captcha.click(function(event){
                event.stopPropagation();
            });

            captchaImg.click(function(event){
                event.stopPropagation();
            });

            loginBtn.click(function(event){
                event.stopPropagation();
            });

            cancelBtn.click(function() {
                window.location.href = "/index.html";
            });

            userName.blur(function(){
                var value = jQuery(this).val();
                var oldval = jQuery(this).attr("oldval");

                if(value != null && jQuery.trim(value).length > 0 && value != oldval) {
                    jQuery(this).attr("oldval", value);
                    password.val("");
                }
            });

            captcha.focus(function(){
                var value = userName.val();
                jQuery(document).keydown(keydown);

                if(value != null && jQuery.trim(value).length > 0) {
                    if(captcha.attr("initialized") == null) {
                        form.getCaptcha();
                    }
                }
            });

            captcha.blur(function(){
                jQuery(document).unbind("keydown", keydown);
            });

            captchaImg.click(function(){
                if(jQuery.trim(userName.val()).length > 0 && jQuery.trim(password.val()).length) {
                    form.getCaptcha();
                }
            });

            form.find(".captchabtn").click(function(){
                captchaImg.click();
            });

            form.find(".registe").click(function(){
                window.location.href = PageContext.getContextPath() + "/passport/registe.html?location=" + encodeURIComponent(window.location.href);
                return true;
            });

            form.find(".forgot").click(function(){
                window.location.href = PageContext.getContextPath() + "/passport/forgot.html?location=" + encodeURIComponent(window.location.href);
                return true;
            });
        }

        loginBtn.unbind("click");
        loginBtn.click(function(){
            if(jQuery.trim(userName.val()) == "") {
                alert("请输入登录用户名！");
                return false;
            }

            if(jQuery.trim(password.val()) == "") {
                alert("请输入密码！");
                return false;
            }

            /*
            if(jQuery.trim(captcha.val()) == "") {
                alert("请输入验证码！");
                return false;
            }
            */

            var loc = form.find("input[name=location]");

            if(loc.val() == null || jQuery.trim(loc.val()).length < 1) {
                loc.val(window.location.href);
            }

            if(form.attr("async") != "true") {
                form.attr("method", "post");
                loginBtn.attr("disabled", true);
                form.submit();
            }
            else {
                var action = form.attr("action");
                var data = {
                    "userName": userName.val(),
                    "password": password.val(),
                    "captcha": captcha.val(),
                    "type": "ajax"
                };

                var parameters = [];

                for(var i in data) {
                    parameters[parameters.length] = i + "=" + encodeURIComponent(data[i]);
                }

                if((action.indexOf("?") > -1) || (action.indexOf("&") > -1) || (action.indexOf("#") > -1)) {
                    action = action + "&" + parameters.join("&");
                }
                else {
                    action = action + "?" + parameters.join("&");
                }

                jQuery.getScript(action, function(response){
                    UserManager.user = UserManager.parse();

                    if(response == null) {
                        response = {"code": -1, "message": "登录失败，请重新登录 !"};
                    }

                    if(response.code == 0) {
                        UserManager.trigger(UserManager.user);
                    }
                    else {
                        captcha.val("");
                        form.getCaptcha();
                    }

                    if(callback != null) {
                        callback(response);
                    }
                });
            }
        });
    },
    getCaptcha: function(check){
        var form = this;
        var src = PageContext.getContextPath() + "/captcha?r=" + (new Date()).getTime();
        form.find("img.captcha").attr("src", src).show();
        form.find("input[name=captcha]").val("");
        form.find("input[name=captcha]").attr("initialized", "true");
        return true;
    }
});

var UserManager = {};

UserManager.parse = function(certificate){
    var passport = (certificate != null ? certificate : CookieUtil.getCookie("passport"));
    var values = (passport != null ? passport.split("|") : []);

    if(values.length >= 6) {
        var user = {};
        user.sessionId = Base64.decode(values[0]);
        user.appId = Base64.decode(values[1]);
        user.userId = Base64.decode(values[2]);
        user.userName = Base64.decode(values[3]);
        user.nickName = Base64.decode(values[4]);
        user.createTime = Base64.decode(values[5]);
        return user;
    }
    return null;
};

UserManager.getUser = function(){
    return this.user;
};

UserManager.login = function(){
};

UserManager.logout = function(){
    UserManager.user = null;
    CookieUtil.setCookie({name: "passport", value: "1", expires: -1, path: "/"});
    window.location.reload();
    return false;
};

window.Base64 = Base64;
window.CookieUtil = CookieUtil;
window.Response = Response;
window.PageContext = PageContext;
window.UserManager = UserManager;
})();

jQuery(function() {
    var user = UserManager.parse();

    if(user == null || user == undefined) {
        UserManager.user = null;
    }
    else {
        UserManager.user = user;
    }
});

jQuery(function() {
    jQuery("form.login").login(function() {
        window.location.reload();
    });

    jQuery("form.register").register(function() {
        window.location.reload();
    });
});

